#! /usr/bin/python2.4
# jhebert@cs.washington.edu

""" Code for the chartManager webserver. """

from util.nodes.StatsServer import WebServer
from util.nodes.StatsServer import QueryListener


def Starter(INPUTS : start, logs, port):
  """ Start of the chart.
  This should actually have state on whether we are currently
  handling the chart, which is updated on emit of start, and
  either then emit the logs to be handled, or do so when they
  are received to begin with. """
  statusLog, commandLog = logs
  emit("log", (statusLog, "stat"))
  emit("log", (commandLog, "command"))
  print 'Starting webserver on port', str(port)
  server = WebServer(('',port), QueryListener)
  server.Init()
  emit("server", server)
  server.StartServing()


def Exiter(INPUTS : exit, list logs):
  """ This should exit the log handler. It would be cool if it
  could do anything important with log commands or status.
  Also, what can I do to clear the queues? """
  emit('exit', 1)
  for logSet in logs:
    for log in logSet:
      log.put(('LogHandler',('_EXIT_'),'LogHandler'))


def Handler(INPUT : log, server):
  """ This is where we should actually be handling the logs.
  So there is the question of how much should be printed out as
  well as when we should be making commands to the chartHandler,
  as really, that is the point here. """
  global log
  log, typeName = log
  while 1:
    item = log.get(True)
    command=item[3]
    if(command=='_EXIT_'):
      return
    elif(command=='_PRINT_'):
      print '_PRINT_ :', item
    elif(command=='_ERROR_'):
      print '_ERROR_ :', item
    elif(command=='_LOAD_'):
      print 'Load is not implemented yet!'
    else:
      server.UpdateLogFromItem(item)
      

def StopRunning(INPUTS : exit, server):
  """ This method closes the webServer when we are all done. """
  server.PleaseShutDown()
